package com.example.javaweb;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.*;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "upload", value = "/upload")
public class UploadServlet extends HttpServlet {

    private final int MAX_FILE_SIZE = 1024 * 1024 * 10;

    private final int MAX_MEN_SIZE = 1024 * 1024 * 10;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            upload(request,response);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置对客户端请求进行重新编码为UTF-8，否则会出现乱码
        request.setCharacterEncoding("UTF-8");
        //指定对服务器响应进行重新编码为UFT-8，同时浏览器也是根据这个参数来就行重写编码(又称解码)
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        // 检查是否有一个文件上传请求
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String savePath = "D:\\jsp\\";
        if (!isMultipart) {
            throw new Exception("非文件类型请求");
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 文件大小的最大值将被存储在内存中
        factory.setSizeThreshold(MAX_MEN_SIZE);
        // 获取项目根目录绝对路径
        String path = getServletContext().getRealPath("");
        // 设置缓存文件的临时存放目录
        factory.setRepository(new File(path + "upload"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 允许上传的文件大小的最大值
        upload.setSizeMax(MAX_FILE_SIZE);
        // 解析请求，获取文件项
        List<FileItem> fileItems = upload.parseRequest(request);
        // 处理上传的文件项
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                System.out.println(fileItem.getFieldName() + " - " + fileItem.getString("UTF-8"));
            }else {
                String fileName = UUID.randomUUID() +getFileType(fileItem.getName());
                String fullPath = savePath+fileName;
                mkdir(fullPath);
                // 写入文件
                File file = new File(fullPath);
                fileItem.write(file);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","上传成功");
        response.getWriter().write(jsonObject.toString());
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public String getFileType(String fileName){
        int lastIndex = fileName.lastIndexOf(".");
        String fileType = "."+fileName.substring(lastIndex+1);
        return fileType;
    }

    /**
     * 创建目录
     * @param path
     * @throws IOException
     */
    public void mkdir(String path) throws IOException {
        File tempFile = new File(path);
        if(!tempFile.getParentFile().exists()){
            tempFile.getParentFile().mkdirs();//创建父级文件路径
            tempFile.createNewFile();//创建文件
        }
    }

}